package com.vincent.shiro;

import com.alibaba.fastjson.JSON;
import com.vincent.common.enums.ResultMapKey;
import com.vincent.common.enums.SessionEnum;
import com.vincent.common.utils.RequestUtil;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义拦截器，判断用户是否登录
 */
public class OnLineFilter extends AccessControlFilter {

    private static final Logger logger = Logger.getLogger(OnLineFilter.class);

    private String noLoginUrl;

    public String getNoLoginUrl() {
        return noLoginUrl;
    }

    public void setNoLoginUrl(String noLoginUrl) {
        this.noLoginUrl = noLoginUrl;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            Object adminObj = subject.getSession().getAttribute(SessionEnum.ADMIN.getCode());
            if (adminObj == null) {
                return false;
            }
            return true;
        }
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();//退出
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;

        boolean isAjax = RequestUtil.isAjax(httpRequest);
        if (isAjax) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put(ResultMapKey.ERROR.getCode(), "请登录");
            try {
                response.getWriter().println(JSON.toJSONString(map));
            } catch (IOException e) {
                logger.error("Error:", e);
            } finally {
                return false;
            }
        }

        String path = httpRequest.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
        httpRequest.getSession().setAttribute(SessionEnum.ERRORMSG.getCode(), "请登录");
        httpResponse.sendRedirect(basePath + getNoLoginUrl());
        return false;
    }

}
